<?php
namespace app\api\controller;

use app\api\model\Advertisement as AdvertisementModel;
use think\Request;
use think\Db;
use think\Exception;

/**
 * 广告API控制器
 * Class Advertisement
 * @package app\api\controller
 */
class Advertisement extends BaseController
{
    /**
     * 获取广告记录
     * @param Request $request
     * @return \think\response\Json
     */
    public function getList(Request $request)
    {
        // 获取请求参数
        $position = $request->param('position', ''); // 广告位置
        $page = $request->param('page', 1); // 页码
        $limit = $request->param('limit', 10); // 每页数量
        
        try {
            // 查询条件
            $where = [
                'status' => 1, // 只获取启用的广告
                'start_time' => ['<=', date('Y-m-d H:i:s')],
                'end_time' => ['>=', date('Y-m-d H:i:s')]
            ];
            
            // 如果指定了广告位置，则按位置筛选
            if (!empty($position)) {
                $where['position'] = $position;
            }
            
            // 查询广告列表
            $ads = AdvertisementModel::where($where)
                ->field('id, title, image, url, position, sort, ad_type, description')
                ->order(['sort' => 'asc', 'id' => 'desc'])
                ->paginate($limit, false, ['page' => $page]);
            
            $result = [
                'data' => $ads->items(),
                'total' => $ads->total(),
                'page' => $page,
                'limit' => $limit,
                'pages' => $ads->lastPage()
            ];
                
            return $this->renderSuccess('获取成功', $result);
        } catch (Exception $e) {
            return $this->renderError('获取广告列表失败：' . $e->getMessage());
        }
    }
    
    /**
     * 获取广告详情
     */
    public function getDetail()
    {
        $ad_id = input('ad_id/d', 0);
        
        if (!$ad_id) {
            return $this->renderError('广告ID不能为空');
        }
        
        try {
            $ad = AdvertisementModel::where([
                'id' => $ad_id,
                'status' => 1,
                'start_time' => ['<=', date('Y-m-d H:i:s')],
                'end_time' => ['>=', date('Y-m-d H:i:s')]
            ])->find();
            
            if (!$ad) {
                return $this->renderError('广告不存在或已过期');
            }
            
            // 增加点击次数
            AdvertisementModel::where('id', $ad_id)->setInc('click_count');
            
            // 记录点击日志
            $this->logAdClick($ad_id, $this->getUserId() ?? 0);
            
            return $this->renderSuccess('获取成功', $ad);
        } catch (Exception $e) {
            return $this->renderError('获取广告详情失败：' . $e->getMessage());
        }
    }
    
    /**
     * 记录广告点击
     */
    public function recordClick()
    {
        $ad_id = input('ad_id/d', 0);
        
        if (!$ad_id) {
            return $this->renderError('广告ID不能为空');
        }
        
        try {
            // 检查广告是否存在且有效
            $ad = AdvertisementModel::where([
                'id' => $ad_id,
                'status' => 1,
                'start_time' => ['<=', date('Y-m-d H:i:s')],
                'end_time' => ['>=', date('Y-m-d H:i:s')]
            ])->find();
            
            if (!$ad) {
                return $this->renderError('广告不存在或已过期');
            }
            
            // 增加点击次数
            AdvertisementModel::where('id', $ad_id)->setInc('click_count');
            
            // 记录点击日志
            $this->logAdClick($ad_id, $this->getUserId() ?? 0);
            
            return $this->renderSuccess('点击记录成功');
        } catch (Exception $e) {
            return $this->renderError('记录点击失败：' . $e->getMessage());
        }
    }
    
    /**
     * 获取轮播图
     */
    public function getBanners()
    {
        $position = input('position/s', 'home');
        
        try {
            $banners = AdvertisementModel::where([
                'position' => $position,
                'ad_type' => 'banner',
                'status' => 1,
                'start_time' => ['<=', date('Y-m-d H:i:s')],
                'end_time' => ['>=', date('Y-m-d H:i:s')]
            ])
            ->field('id, title, image, url, description')
            ->order('sort asc')
            ->limit(5)
            ->select();
            
            return $this->renderSuccess('获取成功', $banners);
        } catch (Exception $e) {
            return $this->renderError('获取轮播图失败：' . $e->getMessage());
        }
    }
    
    /**
     * 获取弹窗广告
     */
    public function getPopup()
    {
        try {
            $popup = AdvertisementModel::where([
                'ad_type' => 'popup',
                'status' => 1,
                'start_time' => ['<=', date('Y-m-d H:i:s')],
                'end_time' => ['>=', date('Y-m-d H:i:s')]
            ])
            ->field('id, title, image, url, description')
            ->order('sort asc')
            ->find();
            
            if ($popup) {
                // 记录展示日志
                $this->logAdShow($popup['id'], $this->getUserId() ?? 0);
            }
            
            return $this->renderSuccess('获取成功', $popup);
        } catch (Exception $e) {
            return $this->renderError('获取弹窗广告失败：' . $e->getMessage());
        }
    }
    
    /**
     * 记录广告展示
     */
    public function recordShow()
    {
        $ad_id = input('ad_id/d', 0);
        
        if (!$ad_id) {
            return $this->renderError('广告ID不能为空');
        }
        
        try {
            // 增加展示次数
            AdvertisementModel::where('id', $ad_id)->setInc('show_count');
            
            // 记录展示日志
            $this->logAdShow($ad_id, $this->getUserId() ?? 0);
            
            return $this->renderSuccess('展示记录成功');
        } catch (Exception $e) {
            return $this->renderError('记录展示失败：' . $e->getMessage());
        }
    }
    
    /**
     * 记录广告点击日志
     * @param int $adId
     * @param int $memberId
     */
    private function logAdClick($adId, $memberId)
    {
        try {
            Db::name('ad_click_logs')->insert([
                'ad_id' => $adId,
                'member_id' => $memberId,
                'ip' => request()->ip(),
                'user_agent' => request()->header('user-agent'),
                'created_at' => date('Y-m-d H:i:s')
            ]);
        } catch (Exception $e) {
            // 记录日志失败不影响主流程
        }
    }
    
    /**
     * 记录广告展示日志
     * @param int $adId
     * @param int $memberId
     */
    private function logAdShow($adId, $memberId)
    {
        try {
            Db::name('ad_show_logs')->insert([
                'ad_id' => $adId,
                'member_id' => $memberId,
                'ip' => request()->ip(),
                'user_agent' => request()->header('user-agent'),
                'created_at' => date('Y-m-d H:i:s')
            ]);
        } catch (Exception $e) {
            // 记录日志失败不影响主流程
        }
    }
}